//
//  CommentsViewController.m
//  DataStatistics
//
//  Created by oilklenze on 16/2/16.
//  Copyright © 2016年 YTYangK. All rights reserved.
//
#import "CommentsViewController.h"
#import "UIImageView+WebCache.h"
#import "Messages.h"
#import "MoreViewController.h"
#import "UploadPhotosViewController.h"
#import "MainTalkAbout.h" //
#import "MJRefreshStateHeader.h"
#import "NSDate+TimeAgo.h"
#import "YMReplyInputView.h"
#import "CoverView.h"
#import "AppDelegate.h"

#define EMOJI_CODE_TO_SYMBOL(x) ((((0x808080F0 | (x & 0x3F000) >> 4) | (x & 0xFC0) << 10) | (x & 0x1C0000) << 18) | (x & 0x3F) << 24);

@interface CommentsViewController ()<DDRichTextViewDataSource,DDRichTextViewDelegate>
{

    NSString *key;
    CoverView *cover;

}
@property (strong,nonatomic) Body                       *messages;//数据桥接
@property (nonatomic       ) int                        page;//页数
@property (nonatomic,strong) UploadPhotosViewController *upimageVC;//上传数据回调对象
@property (nonatomic,strong) UIButton                   *noResult2;//没有结果显示的图片
@end

@implementation CommentsViewController
@synthesize messages    = _messages;
@synthesize ymDataArray = _ymDataArray;
//@synthesize fetchedResultsController =_fetchedResultsController;
@synthesize manageobjectContext = _manageobjectContext;

#pragma mark - 生命周期

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserverForName:DatabaseAvailabilityNotification
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification * _Nonnull note) {
                                                      self.manageobjectContext = note.userInfo[DatabaseAvailabilityContext];
                                                        }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self welcome];
    
    self.mainTable.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    self.page             = 1;
        [self updata];
    }];
    self.mainTable.footer =[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        int i=0;
    
        self.page         = i;
        [self updata];
        i++;
    }];
    [(MJRefreshNormalHeader *)self.mainTable.header lastUpdatedTimeLabel].hidden=YES;
    [self.mainTable.header beginRefreshing];
    self.mainTable.separatorColor = RGB(125, 125, 125, 1);
    [self.mainTable setSeparatorInset:UIEdgeInsetsMake(15, 66, 15, 10)];
    self.delegate                 = self;
    self.dataSource               = self;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updata];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)welcome
{
    cover = [[CoverView alloc]init];
    
    [cover setCoverObjectForKey:key = @"CommentsView"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapView)];
    
    [cover.DevicesView addGestureRecognizer:tap];
}


-(void)TapView
{
    [cover.DevicesView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:key];
    
}



#pragma mark - Segue 方法
//上传回调Block
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    //发送完回调
    __block CommentsViewController*weakself = self;
    self.upimageVC                          = segue.destinationViewController;
    [self.upimageVC setValue:self.commentsDeviceCode forKey:@"uploadPhotosDeviceCode"];
    self.upimageVC.showimage =^(NSMutableArray *images,NSString *text){
        YMTextData *textdat=[[YMTextData alloc]init];
        textdat.showImageArray    = images;
        textdat.smallImageArray   = images;
        textdat.foldOrNot         = YES;
        
        textdat.showShuoShuo      = text;
        textdat.name              = USERNAME;
        textdat.headPicURL=[GET_HEND_IMAGE_IP stringByAppendingString:HEADST];
        textdat.intro             = NSLocalizedString(@"Just now", nil  );
        textdat.localDataNoUpload = YES;
        [weakself.ymDataArray insertObject:textdat atIndex:0];
        [weakself.noResult2 removeFromSuperview];
        [weakself setYmDataArray:weakself.ymDataArray];
    };
    self.upimageVC.updateImageSuccess=^{
                [weakself updata]; //回调上传到服务器后是否刷新
    };
}

#pragma mark - 自定义方法
//更新数据
- (void)updata
{
    NSString *url =@"messages/messages.asp";
    url = [IPHEAD stringByAppendingString:url];
    NSNumber *page =[[NSNumber alloc]initWithInt:self.page];
    NSDictionary *parameter;
    if (self.commentsDeviceCode == nil) {
       parameter = @{@"current_page":page};
    }else {
        parameter = @{@"device_id":self.commentsDeviceCode,@"current_page":page};
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html", nil];
    [manager GET:url parameters:parameter success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        
        [self.mainTable.header endRefreshing];
        [self.mainTable.footer endRefreshing];
        
        NSArray *messages;

        
        if ([responseObject valueForKeyPath:@"body.messages"]) {
            messages = [responseObject valueForKeyPath:@"body.messages"];

            
            if (messages.count != 0) {
                self.messages = [self.messages initWithDictionary:responseObject error:nil];
                [self.noResult2 removeFromSuperview];
            } else {
                if (self.page==1) {
                    [self.mainTable addSubview:[self noResult2]];
                    self.ymDataArray = nil;
                }
                [self.mainTable.footer endRefreshingWithNoMoreData];

            }
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
        [self.mainTable.header endRefreshing];
        [self.mainTable.footer endRefreshing];
        if (error.code ==-1004) {
            [MBProgressHUD showError:NET_ERROR];
        }else{
            [MoreViewController logout:self];
        }
        
    }];
//         [MainTalkAboutViewModel requestWithUrlForMainTalk:self andParam:parameter success:^(NSDictionary *model) {
//             
//         } failure:^(NSString *error) {
//             
//         }];
    
}

#warning  这是什么？？？
//coreData方法
- (void)performFetch
{
    if (self.fetchedResultsController) {
        if (self.fetchedResultsController.fetchRequest.predicate) {
            if (self.debug) NSLog(@"[%@ %@] fetching %@ with predicate: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName, self.fetchedResultsController.fetchRequest.predicate);
        } else {
            if (self.debug) NSLog(@"[%@ %@] fetching all %@ (i.e., no predicate)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName);
        }
        NSError *error;
        BOOL success = [self.fetchedResultsController performFetch:&error];
        if (!success) NSLog(@"[%@ %@] performFetch: failed", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        if (error) NSLog(@"[%@ %@] %@ (%@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [error localizedDescription], [error localizedFailureReason]);
    } else {
        if (self.debug) NSLog(@"[%@ %@] no NSFetchedResultsController (yet?)", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    }
    [self.mainTable reloadData];
    
}

- (void)insertObjectIntoDatabase:(Messages *)messages
{
//    MainTalkAbout *mainTalkAbout = [NSEntityDescription insertNewObjectForEntityForName:@"MainTalkAbout"
//                                                                 inManagedObjectContext:self.manageobjectContext];

}
#pragma mark - delegate
#pragma mark  DDRichTextViewDataSource and DDRichTextViewDelegate

//朋友圈的用户名
- (NSString *)senderName{
    return USERNAME;
}

//朋友圈是否显示delete
- (BOOL)hiddenDeleteBtnFromText:(NSInteger)index name:(NSString *)name {
    return ![name isEqualToString:USERNAME];
}


//cell行数
- (NSInteger)numberOfRowsInDDRichSection:(NSInteger)section {
//     id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
//    NSInteger row = [sectionInfo numberOfObjects];
    return [self.ymDataArray count];
}

#warning 这里是数据传入方法
//数据源
- (YMTextData *)dataForRowAtIndex:(NSInteger)index {
    
    return [self.ymDataArray objectAtIndex:index];

}
//是否显示回复按钮
- (BOOL)hideReplyButtonForIndex:(NSInteger)index {
    return NO;
}

//点击头像激活此方法
- (void)didPromulgatorNameOrHeadPicPressedForIndex:(NSInteger)index name:(NSString *)name{

}

//点击正文激活此方法
- (void)didRichTextPressedFromText:(NSString*)text index:(NSInteger)index{

}

#pragma mark - 删除Cell
- (void)deleteCellForindex:(NSIndexPath *)indexPath {
    UIAlertAction *sureAction =[UIAlertAction actionWithTitle:NSLocalizedString(@"Delete",nil )style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSNumber *commentPK =[[NSNumber alloc]initWithInt:((YMTextData *)self.ymDataArray[indexPath.row]).pk];
        NSDictionary *parameter =@{@"publishType":@1,@"contentID":commentPK};
        [self updataReplyURL:@"messages/deleteMessage.asp" withPar:parameter returnVlue:^(NSDictionary *reusltDic) {
              //      [self updata];
            NSLog(@"reuslt--->%@",reusltDic);
            [self.mainTable beginUpdates];
            [self.ymDataArray removeObjectAtIndex:indexPath.row];
            [self.mainTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
            [self.mainTable  endUpdates];
        }];
        
        //do something。。
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", "取消")  style:UIAlertActionStyleCancel handler:nil];
    UIAlertController *alerController =[UIAlertController alertControllerWithTitle:NSLocalizedString(@"Confirm deletion", "确认删除？")  message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alerController addAction:sureAction];
    [alerController addAction:cancelAction];
    [self presentViewController:alerController animated:YES completion:nil];
    
}
#pragma mark - 删除回复
- (void)didRichTextPressedFromText:(NSString *)text index:(NSInteger)index replyIndex:(NSInteger)replyIndex{
  
    NSRange range = [text rangeOfString:@"->"];//获取":"的位置
    NSString *usename = [text substringFromIndex:range.location +
                         range.length];//开始截取
    if ([USERNAME isEqualToString:usename]) {
            YMTextData *textData =self.ymDataArray[index];
            NSString *comments =textData.replyDataSource[replyIndex];
            NSLog(@"id:%@--->%@",textData.commentsPk[replyIndex],comments);
            NSNumber *commentPk=[textData commentsPk][replyIndex];
            
            UIAlertController *alertController =[UIAlertController alertControllerWithTitle:NSLocalizedString(@"Delete My Comment", "删除我的评论")  message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *delete=[UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", "删除") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                 NSDictionary *parameter =@{@"publishType":@2,@"commentID":commentPk};
                [self updataReplyURL:@"messages/deleteMessage.asp" withPar:parameter returnVlue:^(NSDictionary *reusltDic) {
                    comments?[textData.replyDataSource removeObjectAtIndex:replyIndex] :nil;
                    commentPk?[textData.commentsPk removeObjectAtIndex:replyIndex]: nil;
                    [self.mainTable reloadData];
                }];
             
            }];
        
            [alertController addAction:delete];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            
                   [self presentViewController:alertController animated:YES completion:nil];
    }
}
#pragma mark - 请求方法
- (void)updataReplyURL:(NSString *)url withPar:(NSDictionary *)parameter returnVlue:(void (^)(NSDictionary *reusltDic))vlue{
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:url requestWithParameters:parameter method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        int  resultInt  =[[[objs objectForKey:@"body"] objectForKey:@"result"] intValue];
        if (resultInt == 1) {
            vlue([objs objectForKey:@"body"]);
        }else {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"删除失败" toView:nil];
        }
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:nil];
    }];

}
#pragma mark - 回复方法
- (void)replyForIndex:(NSInteger)index replyText:(NSString*)text{
    text=[text removeEmoji];
    if (text) {
        YMTextData *textData = self.ymDataArray[index];
         NSNumber *pk =[[NSNumber alloc]initWithInt:textData.pk];
        NSDictionary *parameter =@{@"content":text,@"publishType":@2,@"contentID":pk};
        [self updataReplyURL:@"messages/publishMessage.asp" withPar:parameter returnVlue:^(NSDictionary *reusltDic) {
            NSNumber *num  = [NSNumber numberWithInt:[reusltDic[@"pk"] intValue]];
            [textData.commentsPk addObject:num];
           
        }];
    }

}

#pragma mark - 数据跟踪方法
- (NSFetchedResultsController *)CfetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    
    NSFetchRequest *fectchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MainTalkAbout" inManagedObjectContext:self.manageobjectContext];
    [fectchRequest setEntity:entity];
    [fectchRequest setFetchBatchSize:100];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"publishTime" ascending:YES selector:@selector(localizedStandardCompare:)];//排序。。
    [fectchRequest setSortDescriptors:@[sortDescriptor]];
    
    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fectchRequest managedObjectContext:self.manageobjectContext sectionNameKeyPath:nil cacheName:nil];
    fetchedResultsController.delegate = self;
    
    self.fetchedResultsController = fetchedResultsController;
    NSError *erro = nil;
    if (![self.fetchedResultsController performFetch:&erro]) {
        NSLog(@"Unresolved error %@, %@",erro,[erro userInfo]);
        abort();
    }
    return _fetchedResultsController;
}


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.mainTable beginUpdates]; //开始变化
}
// 跟踪 Section 的变化
- (void) controller:(NSFetchedResultsController *)controller
   didChangeSection:(id <NSFetchedResultsControllerDelegate>)sectionInfo
            atIndex:(NSUInteger)sectionIndex
    forChangeType:(NSFetchedResultsChangeType)type {
    
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.mainTable insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; // 插入数据
            break;
        case NSFetchedResultsChangeDelete:
            [self.mainTable deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; //删除数据
            break;
        default:
            break;
    }
    
}


// 跟踪数据对象的变化
- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    
    UITableView *tableView = self.mainTable;
    
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeUpdate:
            //这里更新数据
            break;
        case NSFetchedResultsChangeMove:
            [tableView moveRowAtIndexPath:indexPath toIndexPath:newIndexPath]; //移动
        default:
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.mainTable endUpdates]; //结束变化
}

#pragma mark - getter setter
//更新数据源
- (void)setMessages:(Body *)messages
{
    
    _messages=messages;
    
    self.page==1?[self.ymDataArray removeAllObjects]:nil;
    for (int i=0; i<messages.messages.count; i++) {
        [MainTalkAbout mainTalkAboutWithMessages:(Messages *)messages.messages[i] inManagedObjectContext:self.manageobjectContext];
        YMTextData *ymTextData =[[YMTextData alloc]init];
//        设置图片
        NSMutableArray *smallImageArry =[[NSMutableArray alloc]init];
        NSMutableArray *imageArray;
        imageArray =[((Messages *)messages.messages[i]).images mutableCopy];
        if (imageArray && imageArray.count!=0) {
            for (int i=0;i<imageArray.count;i++) {
                if ([imageArray[i] isKindOfClass:[NSString class]]) {
                    NSString *smallImage = [NSString stringWithFormat:@"%@thumb_%@",GET_COMMENTS_IMAGE_IP,imageArray[i]];
                    [smallImageArry addObject:smallImage];
                    NSString *st =[GET_COMMENTS_IMAGE_IP stringByAppendingString: imageArray[i] ];
                    [imageArray replaceObjectAtIndex:i withObject:st];
                }
            }
            ymTextData.showImageArray  = imageArray;
            ymTextData.smallImageArray = smallImageArry;
            
        }else{
            ymTextData.showImageArray =nil;
            ymTextData.smallImageArray=nil;
        }
        
        ymTextData.foldOrNot    = YES;//是否有收起
        ymTextData.showShuoShuo = ((Messages *)messages.messages[i]).content;
        
        //不知道是怎么设置  什么鬼东西
//        ymTextData.defineAttrData =nil;
        NSMutableArray *commentsOnContent = [[NSMutableArray alloc]init];
        NSMutableArray *commentsPk        = [[NSMutableArray alloc]init];
        for ( Comments *comments in ((Messages *)messages.messages[i]).comments) {
            NSNumber *number=[[NSNumber alloc]initWithInt:comments.commentPK];
            if (comments) {
                comments.user_name?nil:(comments.user_name=@"");comments.commentContent?nil:(comments.commentContent=@"");

                
                
                NSString *usrnameAndcontent=[NSString stringWithFormat:@"%@:%@",comments.user_name,comments.commentContent];
                
                
                
                [commentsOnContent addObject:usrnameAndcontent];
            }
            [commentsPk addObject:number];
        }
        ymTextData.replyDataSource = commentsOnContent;
        ymTextData.pk              = ((Messages *)[messages messages][i]).pk;
        ymTextData.commentsPk      = commentsPk;
        //----------------->>
        //设置用户名
        ymTextData.name            = [[messages messages][i] user_name];
        //设置头像
        ymTextData.headPicURL      = ((Messages *)messages.messages[i]).user_image;
        ymTextData.intro           = ((Messages *)messages.messages[i]).publishTime;
        NSString *age = [UtilToolsClss timeAgeWithChinaTimeTransformCurrentPhoneTimeZooe:((Messages *)messages.messages[i]).publishTime];
        ymTextData.intro = age;
        [self.ymDataArray addObject:ymTextData];
    }
    [self setYmDataArray:self.ymDataArray];
}

- (Body *)messages
{

    if (!_messages) {
        _messages =[[Body alloc]init];
    }

    return _messages;
}

- (int)page{
    if (_page==0) {
    _page        = 1;
    }
    return _page;
}

- (NSMutableArray *)ymDataArray  {
    if (!_ymDataArray) {
    _ymDataArray = [[NSMutableArray alloc]init];
    }
    return _ymDataArray;
}

- (void)setYmDataArray:(NSMutableArray *)ymDataArray {
    _ymDataArray = ymDataArray;
    [self.mainTable reloadData];

}

- (UIButton *)noResult2 {
    if (!_noResult2) {
        _noResult2                        = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/4, SCREEN_WIDTH/4, SCREEN_WIDTH/2, SCREEN_WIDTH/2)];
        _noResult2.userInteractionEnabled = NO;
        [_noResult2 setTitle:NSLocalizedString(@"No Results", "没有结果") forState:UIControlStateNormal];
        [_noResult2 setTitleColor:RGB(140, 140, 140, 1) forState:UIControlStateNormal];
        _noResult2.layer.cornerRadius     = SCREEN_WIDTH/2/2;
        _noResult2.layer.masksToBounds    = YES;
        [_noResult2 setBackgroundColor:RGB(125, 125, 125, 0.1)];
        
    }
    return _noResult2;
}


#pragma mark FetcherResultsAndMangedObjectContext
//FetchedResultsController setter 方法
//- (void)setFetchedResultsController:(NSFetchedResultsController *)newfrc
//{
//    NSFetchedResultsController *oldfrc = _fetchedResultsController;
//    if (newfrc !=oldfrc) {
//        _fetchedResultsController   = newfrc;
//
////        newfrc.delegate = self;
//        if (newfrc) {
//            if (self.debug) NSLog(@"[%@ %@]%@",NSStringFromClass([self class]), NSStringFromSelector(_cmd  ),oldfrc ? @"updated" : @"set");
//            [self performFetch];
//            
//        }else {
//            if (self.debug) NSLog(@"[%@ %@] reset to nil",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
//            [self.mainTable reloadData];
//        }
//    }
//}

//- (void)setManageobjectContext:(NSManagedObjectContext *)manageobjectContext
//{
//    _manageobjectContext = manageobjectContext;
//    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainTalkAbout"];
//    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"publishTime"
//                                                              ascending:YES
//                                                               selector:@selector(localizedStandardCompare:)]];
////    request.sortDescriptors = nil;
//    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
//                                                                       managedObjectContext:manageobjectContext
//                                                                         sectionNameKeyPath:nil cacheName:nil];
//}

- (NSManagedObjectContext *)manageobjectContext {
    if (!_manageobjectContext) {
        _manageobjectContext  =  [self appDelegate].managedObjectContext;
    }
    return _manageobjectContext;
}

- (AppDelegate*) appDelegate {
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

@end
